package com.qnvip.sbd.util;

import org.apache.commons.lang3.StringUtils;

public class PasswordUtil {
	/**
	 * 生成含有随机盐的密码
	 * 
	 * @param password input password
	 */
	public static String password(String password) {
		String salt = StringUtil.getRandomString(16).toUpperCase();
		password = md5(password + salt);
		char[] result = new char[48];
		for (int i = 0; i < 48; i += 3) {
			result[i] = password.charAt(i / 3 * 2);
			result[i + 1] = salt.charAt(i / 3);
			result[i + 2] = password.charAt(i / 3 * 2 + 1);
		}
		return new String(result);
	}

	/**
	 * 校验密码是否正确
	 * 
	 * @param original 	明文
	 * @param cipher 	密文
	 */
	public static boolean verify(String original, String cipher) {
		if (StringUtils.isBlank(original))
			return false;
		if (StringUtils.length(cipher) != 48)
			return false;
		char[] md5s = new char[32], salts = new char[16];
		for (int i = 0; i < 48; i += 3) {
			md5s[i / 3 * 2] = cipher.charAt(i);
			md5s[i / 3 * 2 + 1] = cipher.charAt(i + 2);
			salts[i / 3] = cipher.charAt(i + 1);
		}
		return StringUtils.equals(md5(original + new String(salts)), new String(md5s));
	}
	
	private static String md5(String original) {
		MD5 md5 = new MD5();
		String cipher = md5.getMD5ofStr(original);
		String a = md5.getMD5ofStr(cipher.substring(0, 16));
		String b = md5.getMD5ofStr(cipher.substring(16));
		return md5.getMD5ofStr(b + a);
	}
	
	public static void main(String[] args) {
		String p = password("123456");
		System.out.println(p);
		System.out.println(verify("123456", p));
	}
}
